package com.rudolfheszele.smsselector.controller;

import java.util.Date;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.rudolfheszele.smsselector.R;
import com.rudolfheszele.smsselector.model.SmsSelectorSmsMessage;
import com.rudolfheszele.smsselector.view.SmsSelectorMessageViewerActivity;
import com.rudolfheszele.smsselector.view.SmsSelectorRuleCreatorActivity;
import com.rudolfheszele.smsselector.view.View;

public class SmsSelectorMessageViewerActivityController implements Controller
{
	public static final String FOLDER_KEY = "folder";
	public static final String MESSAGE_ID_KEY = "message_id";
	
	public SmsSelectorMessageViewerActivityController(Activity activity)
	{	
		mViewerActivity = (SmsSelectorMessageViewerActivity)activity;
		mMainController = (SmsSelectorMainController)ControllerFactoryFactory.getControllerFactory().getController();
		mMessage = null;
		mRuleCreatorIntent = null;
		registerMessageViewerActivity();
	}

	@Override
	public View getView(int viewId)
	{
		return mViewerActivity;
	}

	@Override
	public void registerView(View view)
	{
		this.mViewerActivity = (SmsSelectorMessageViewerActivity)view;
		registerMessageViewerActivity();
	}
	
	@Override
	public void updateView(View view)
	{
		// Nothing to do yet...
	}

	@Override
	public void updateGui(int viewId, Runnable task)
	{
		mViewerActivity.runOnUiThread(task);
	}
	
	@Override
	public boolean buildMenu(View view, Object menu, Object clicked)
	{
		MenuInflater inflater = mViewerActivity.getMenuInflater();
		Menu optionsMenu = (Menu)menu;
		
		inflater.inflate(R.menu.smsselector_message_viewer_activity_options_menu, optionsMenu);
		
		return true;
	}
	
	@Override
	public boolean menuClicked(View view, Object menu)
	{
		MenuItem menuItem = (MenuItem)menu;
		
		if(menuItem.getItemId() == R.id.message_viewer_activity_create_rule_options_menu_id)
		{
			mRuleCreatorIntent = new Intent(mViewerActivity, SmsSelectorRuleCreatorActivity.class);
			
			// The NEW_RULE is true by default
			mRuleCreatorIntent.putExtra(SmsSelectorRuleCreatorActivityController.FROM_MESSAGE, true);
			mRuleCreatorIntent.putExtra(SmsSelectorRuleCreatorActivityController.MESSAGE_TEXT, mMessage.getBody());
			mRuleCreatorIntent.putExtra(SmsSelectorRuleCreatorActivityController.MESSAGE_SENDER, mMessage.getAddress());
			mRuleCreatorIntent.putExtra(SmsSelectorRuleCreatorActivityController.MESSAGE_DATE, mMessage.getDate());
			
			mViewerActivity.startActivity(mRuleCreatorIntent);
		}
		
		return false;
	}
	
	/**
	 * @see Controller
	 */
	@Override
	public void saveState(int viewId, Object state)
	{
		// Nothing to save
	}
	
	/**
	 * @see Controller
	 */
	@Override
	public void restoreState(int viewId, Object state)
	{
		// Nothing to restore, registering the new activity is enough
	}
	
	private void registerMessageViewerActivity()
	{
		Intent intent = null;
		LinearLayout mainLinearLayout = null;
		
		mainLinearLayout = (LinearLayout)mViewerActivity.findViewById(R.id.message_viewer_activity_linear_layout_id);
		intent = mViewerActivity.getIntent();
		mMessage = mMainController.findSmsMessage(intent.getIntExtra(SmsSelectorMessageViewerActivityController.MESSAGE_ID_KEY, -1), intent.getStringExtra(SmsSelectorMessageViewerActivityController.FOLDER_KEY));
		if(mMessage == null)
		{
			TextView headTextView = new TextView(mViewerActivity);
			
			headTextView.setText("No messages found!!!");
			mainLinearLayout.addView(headTextView);
			return;
		}
		displayMessage(mainLinearLayout);
	}
	
	private void displayMessage(LinearLayout linearLayout)
	{
		TextView fromTextView = new TextView(mViewerActivity);
		TextView dateTextView = new TextView(mViewerActivity);
		TextView bodyTextView = new TextView(mViewerActivity);
		android.view.View separatorView = new android.view.View(mViewerActivity);
		String name = mMessage.getPersonName();
		Date date = new Date(mMessage.getDate());
		
		if(name == null)
		{
			name = getNameFromId(getIdFromAddress(mMessage.getAddress()));
			// Store the found name, so we will not need to reread it again from the database
			mMessage.setPersonName(name);
		}
		if(name == null)
			name = "unknown (" + mMessage.getAddress() + ")";
		if(mMessage.getType().equals(SmsSelectorSmsMessage.Type.Received))
			fromTextView.setText("From: " + name);
		else
			fromTextView.setText("To: " + name);
		dateTextView.setText("Date: " + date);
		bodyTextView.setText(mMessage.getBody());
		separatorView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 2));
		separatorView.setBackgroundColor(0xFF909090);
		separatorView.setPadding(0, 5, 0, 5);
		linearLayout.addView(fromTextView);
		linearLayout.addView(dateTextView);
		linearLayout.addView(separatorView);
		linearLayout.addView(bodyTextView);
	}
	
	private String getNameFromId(long id)
	{
		String[] column = new String[] {ContactsContract.Contacts.DISPLAY_NAME};
		Cursor cursor = mViewerActivity.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, column, ContactsContract.Contacts._ID + "=" + id, null, null);
		String name = null;
		 
		if(cursor != null)
		{
			try
			{
				cursor.moveToFirst();
				if(cursor.getCount() > 0)
					name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
			}
			finally
			{
				cursor.close();
			}
		} 
		
		return name;
	}
	
	private long getIdFromAddress(String address)
	{
		Uri uri = Uri.withAppendedPath(Phone.CONTENT_FILTER_URI, address);
		String[] column = new String[] {Phone.CONTACT_ID};
		Cursor cursor = mViewerActivity.getContentResolver().query(uri, column, null, null, null);
		long id = -1;
		
		if(cursor != null)
		{
			try
			{
				cursor.moveToFirst();
				if(cursor.getCount() > 0)
					id = cursor.getLong(cursor.getColumnIndex(Phone.CONTACT_ID));
			}
			finally
			{
				cursor.close();
			}
		}
		if(id == -1 && address.startsWith("+"))
		{
			// No entry were found. Maybe the address in the contacts are not in an international form
			// So change the +36 prefix to 06
			String newAddress = "06" + address.substring(3);
			
			id = getIdFromAddress(newAddress);
		}
		
		return id;
	}
	
	private SmsSelectorMessageViewerActivity mViewerActivity;
	private SmsSelectorMainController mMainController;
	private SmsSelectorSmsMessage mMessage;
	private Intent mRuleCreatorIntent;
}
